// 导入数据库模型操作模块
const mongoose = require('mongoose');
const {
  createPaper,
  isExist,
  getPapers,
  getPaperById,
  deletePaperById,
  deletePapersByIds,
  updatePaperById,
  getUserPapersCount,
} = require('../models/paperModel');
const { updateUserPapers, getUserPapersid } = require('../models/userModel');
const { deleteAnswersByPaperid } = require('../models/answerModel');

module.exports = {
  // 创建问卷的处理函数
  async createPaper(req, res) {
    // console.log(req.user._id);
    const paperData = { userid: req.user._id, ...req.body };
    const useridExist = await isExist('userid', req.user._id);
    // console.log(useridExist);
    if (useridExist) {
      const papernameExist = await isExist('papername', req.body.papername);
      if (papernameExist) return res.sendMess('问卷名已存在');
    }
    const createRes = await createPaper(paperData);
    const updataUserinfo = await updateUserPapers(req.user._id, {
      $addToSet: { paperid: createRes._id },
    });
    // console.log('create', createRes);
    if (!createRes || !updataUserinfo)
      return res.sendMess('创建失败，请稍后再试！');
    res.send({
      meta: { msg: '创建成功!', status: 200 },
      data: { id: createRes._id },
    });
    // res.sendMess('创建成功!', 201);
  },
  // 获取问卷的处理函数
  async getPapers(req, res) {
    //获取当前用户的问卷id
    const papersid = await getUserPapersid(req.user._id);
    const count = await getUserPapersCount(req.query, papersid);
    const result = await getPapers(req.query, papersid);
    if (!result) return res.sendMess('获取问卷信息失败！');
    res.send({
      meta: { msg: '获取问卷成功！', status: 200 },
      data: { papers: result, count },
    });
  },
  // 根据id获取单个问卷的处理函数
  async getPaperById(req, res) {
    const result = await getPaperById(req.params.id);
    if (!result) return res.sendMess('问卷信息不存在！');
    // console.log(result.paperinfo);
    // console.log(req.params);
    if (!req.query.data && JSON.stringify(result.paperinfo) !== '{}') {
      result.paperinfo.items.forEach((el, index) => {
        result.paperinfo.items[index] = Object.keys(el);
      });
    }
    res.send({
      meta: { msg: '获取问卷成功！', status: 200 },
      data: result,
    });
  },
  // 根据ID删除问卷处理函数
  async deletePaperById(req, res) {
    const paperResult = await deletePaperById(req.params.id);
    const userResult = await updateUserPapers(req.user._id, {
      $pull: { paperid: mongoose.Types.ObjectId(req.params.id) },
    });
    if (!paperResult.deletedCount || !userResult.modifiedCount) {
      return res.sendMess('删除问卷信息失败！');
    }
    const papersid = await getUserPapersid(req.user._id);
    const count = await getUserPapersCount(req.query, papersid);
    const result = await getPapers(req.query, papersid);
    if (!result) return res.sendMess('获取问卷信息失败！');
    res.send({
      meta: { msg: '删除问卷成功！', status: 200 },
      data: { papers: result, count },
    });
  },
  // 根据多个ID批量删除问卷
  async deletePapersByIds(req, res) {
    const result = await deletePapersByIds(req.body.ids);
    if (!result.deletedCount) return res.sendMess('删除多个问卷失败！');
    res.sendMess('删除问卷成功！', 200);
  },
  // 根据ID编辑问卷信息
  async updatePaperById(req, res) {
    // 添加选项的选择人数
    const itemsArr = req.body.paperinfo.items;
    req.body.paperinfo.items.forEach((title, index) => {
      const itemsObj = {};
      title.forEach(el => {
        itemsObj[el] = 0;
      });
      itemsArr[index] = itemsObj;
    });
    req.body.paperinfo.items = itemsArr;
    req.body.answersid = [];
    // console.log(req.body);

    const result = await updatePaperById(req.params.id, req.body);
    if (!result.modifiedCount) {
      return res.sendMess('修改问卷失败！');
    }
    const answerResult = await deleteAnswersByPaperid(req.params.id);
    res.sendMess('修改问卷成功！', 200);
  },
  // 判断字段值是否存在
  async isExist(req, res) {
    const { field, value } = req.query;
    const result = await isExist(field, value);
    console.log(result);
    if (!result) {
      return res.sendMess('没有此字段值的记录！');
    }
    res.sendMess('查询字段成功', 200);
  },
};
